package com.zqq.horizontalprogress;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.zqq.circleprogress.R;

/**
 * https://github.com/Tamsiree/RxTool
 */
public class Main3Activity extends AppCompatActivity {

    RxProgressBar mFlikerbar;
    Thread downLoadThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        mFlikerbar = findViewById(R.id.rx_progressbar);

        downLoad();
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mFlikerbar.setProgress(msg.arg1);
            if (msg.arg1 == 100) {
                mFlikerbar.finishLoad();
            }
        }
    };

    private void initFlikerProgressBar() {
        if (!mFlikerbar.isFinish()) {
            mFlikerbar.toggle();
            if (mFlikerbar.isStop()) {
                downLoadThread.interrupt();
            } else {
                downLoad();
            }
        }
    }

    public void reLoad(View view) {
        downLoadThread.interrupt();
        // 重新加载
        mFlikerbar.reset();

        downLoad();
    }

    private void downLoad() {
        downLoadThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (!downLoadThread.isInterrupted()) {
                        float progress = mFlikerbar.getProgress();
                        progress += 2;
                        Thread.sleep(200);
                        Message message = handler.obtainMessage();
                        message.arg1 = (int) progress;
                        handler.sendMessage(message);
                        if (progress == 100) {
                            break;
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });


        downLoadThread.start();
    }

    public void onClick(View view) {
        initFlikerProgressBar();
    }

    public void Reset(View view) {
        reLoad(view);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        downLoadThread.interrupt();
    }


}
